<?php

use think\Db;
use think\Cache;

// 公共助手函数

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '') {
        if (is_numeric($name) || !$name)
            return $name;
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }

}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int $size 大小
     * @param string $delimiter 分隔符
     * @return string
     */
    function format_bytes($size, $delimiter = '') {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++)
            $size /= 1024;
        return round($size, 2) . $delimiter . $units[$i];
    }

}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int $time 时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s') {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }

}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time 时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null) {
        return \fast\Date::human($time, $local);
    }

}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string $url 资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false) {
        $url = preg_match("/^https?:\/\/(.*)/i", $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
        if ($domain && !preg_match("/^(http:\/\/|https:\/\/)/i", $url)) {
            if (is_bool($domain)) {
                $public = \think\Config::get('view_replace_str.__PUBLIC__');
                $url = rtrim($public, '/') . $url;
                if (!preg_match("/^(http:\/\/|https:\/\/)/i", $url)) {
                    $url = request()->domain() . $url;
                }
            } else {
                $url = $domain . $url;
            }
        }
        return $url;
    }

}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param    string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file) {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === FALSE) {
                return FALSE;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return TRUE;
        } elseif (!is_file($file) OR ( $fp = @fopen($file, 'ab')) === FALSE) {
            return FALSE;
        }
        fclose($fp);
        return TRUE;
    }

}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname 目录
     * @param bool $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true) {
        if (!is_dir($dirname))
            return false;
        $files = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }

}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest 目标文件夹
     */
    function copydirs($source, $dest) {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
        $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }

}

if (!function_exists('mb_ucfirst')) {

    function mb_ucfirst($string) {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }

}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items 数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields) {
        if (!$items || !$fields)
            return $items;
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
                }
            }
        }
        return $items;
    }

}

if (!function_exists('var_export_short')) {

    /**
     * 返回打印数组结构
     * @param string $var 数组
     * @param string $indent 缩进字符
     * @return string
     */
    function var_export_short($var, $indent = "") {
        switch (gettype($var)) {
            case "string":
                return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
            case "array":
                $indexed = array_keys($var) === range(0, count($var) - 1);
                $r = [];
                foreach ($var as $key => $value) {
                    $r[] = "$indent    "
                            . ($indexed ? "" : var_export_short($key) . " => ")
                            . var_export_short($value, "$indent    ");
                }
                return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
            case "boolean":
                return $var ? "TRUE" : "FALSE";
            default:
                return var_export($var, TRUE);
        }
    }

}

/**
 * 获取购物车总商品数和总价格
 * @param int $user_id 用户ID
 * @param int $user_box_id 用户盒子ID
 * @return array
 */
function getCartTotalByUserId($user_id, $user_box_id = 0) {
    //购物车数量及价格
    $cart['num'] = Db::name('cart')
            ->alias('c')
            ->join('fa_user_box_goods ubg', 'ubg.box_goods_id = c.box_goods_id')
            ->where(['c.user_id' => $user_id, 'c.user_box_id' => $user_box_id, 'c.type' => 0, 'ubg.is_del' => 0])
            ->sum('buy_num');

    $total_price = Db::name('cart')
            ->fieldRaw('SUM(buy_num*ubg.selling_price) as total_price')
            ->alias('c')
            ->join('fa_user_box_goods ubg', 'ubg.box_goods_id = c.box_goods_id')
            ->where(['c.user_id' => $user_id, 'c.user_box_id' => $user_box_id, 'c.type' => 0, 'ubg.is_del' => 0])
            ->find();

    $cart['total_price'] = $total_price['total_price'] ? $total_price['total_price'] : 0.00;

    return $cart;
}

/**
 * 获取某件商品购物车内的数量
 * @param int $user_id 用户ID
 * @param int $box_goods_id 盒子商品的ID
 * @return array
 */
function getCardNumByGoods($user_id, $box_goods_id) {
    $cwhere['user_id'] = $user_id;
    $cwhere['box_goods_id'] = $box_goods_id;
    $cwhere['type'] = 0;

    $buy_num = Db::name('cart')->where($cwhere)->value('buy_num');

    return $buy_num ? $buy_num : 0;
}

/**
 * 领取优惠券
 * @param int $user_id 用户ID
 * @param int $coupon_id 优惠券ID
 * @return bool
 */
function receiveCoupon($user_id, $coupon_id) {
    $coupon_info = db('coupon')->where('coupon_id', $coupon_id)->find();

    if (empty($coupon_info)) {
        return false;
    }

    $coupon_count = db('user_coupon')->where('user_id', $user_id)->where('coupon_id', $coupon_info['coupon_id'])->count();

    $coupon_all_count = db('user_coupon')->where('coupon_id', $coupon_info['coupon_id'])->count();

    if (($coupon_count < $coupon_info['receive_num']) && ($coupon_all_count < $coupon_info['circulation'])) {

        $data['coupon_id'] = $coupon_id;
        $data['user_id'] = $user_id;

        if ($coupon_info['expiry_type'] == 0) {
            $data['expiry_start'] = date('Y-m-d H:i:s');
            $data['expiry_end'] = date('Y-m-d H:i:s', strtotime("+" . $coupon_info['expiry'] . " day"));
        } else {
            $data['expiry_start'] = $coupon_info['expiry_start'];
            $data['expiry_end'] = $coupon_info['expiry_end'];
        }

        db('user_coupon')->insert($data);
    } else {
        return false;
    }
    return true;
}

/**
 * 生成验证码
 * @param string $strKey 缓存KEY
 * @return string 
 */
function createVerify($phone) {
    $strRand = mt_rand(1000, 9999);
    Cache::set($phone, $strRand, 3600);
    send_sms($phone, $strRand, 1);
    return $strRand;
}

/**
 * 验证码发送 
 */
function send_sms($phone, $strRand, $type) {
    $acc['URL'] = 'http://v.juhe.cn/sms/send';
    $acc['appkey'] = '85b2e3a239d2821b22909f4d338eeb9c';
    $acc['MSG_ID'][1] = '95336';
    $value = urlencode('#code#=' . $strRand);
    $url = $acc['URL'] . '?key=' . $acc['appkey'] . '&tpl_value=' . $value . '&mobile=' . $phone . '&tpl_id=' . $acc['MSG_ID'][$type];
    //$url = $acc['URL'] . '?userCode=' . $acc['USER_CODE'] . '&userPass=' . $acc['USER_PASS'] . '&DesNo=' . $phone . '&Msg=' . $text . '&Channel=0';
    $result_xml = file_get_contents($url);

    return $result_xml;
//    var_dump($result_xml);die;
//    $xml = simplexml_load_string($result_xml);
//    return (string) $xml [0];
}

/**
 * 可用优惠券列表
 * @param int $user_id 用户ID
 * @param int $user_box_id 盒子ID
 * @return bool
 */
function couponList($user_id, $user_box_id) {
    $list = db('user_coupon')
            ->alias('uc')
            ->field('uc.*,c.coupon_name,c.par_value,c.use_condition,c.range,c.relation_id')
            ->join('fa_coupon c', 'uc.coupon_id = c.coupon_id')
            ->where('uc.status', 0)
            ->where('user_id', $user_id)
            ->order('user_coupon_id desc')
            ->select();

    if ($list) {
        foreach ($list as $key => &$val) {
            $val['expiry_end'] = date('Y-m-d', strtotime($val['expiry_end']));
            $val['usetime'] = date('Y-m-d', strtotime($val['usetime']));

            $val['name'] = '全场通用';

            if ($val['range'] == 0) {
                $goods_total = db('cart')
                        ->fieldRaw('SUM(c.buy_num*ubg.selling_price) as total_price')
                        ->alias('c')
                        ->join('user_box_goods ubg', 'c.box_goods_id=ubg.box_goods_id')
                        ->where('c.user_id', $user_id)
                        ->where('c.user_box_id', $user_box_id)
                        ->where('c.type', 0)
                        ->find();

                if ($goods_total['total_price'] < $val['use_condition']) {
                    unset($list[$key]);
                }
            }



            if ($val['range'] == 1) {
                $goods_total = db('cart')
                        ->fieldRaw('SUM(c.buy_num*ubg.selling_price) as total_price')
                        ->alias('c')
                        ->join('user_box_goods ubg', 'c.box_goods_id=ubg.box_goods_id')
                        ->join('goods g', 'ubg.goods_id=g.goods_id')
                        ->join('goods_brand gb', 'g.brand_id=gb.brand_id')
                        ->where('c.user_id', $user_id)
                        ->where('c.user_box_id', $user_box_id)
                        ->where('c.type', 0)
                        ->where('gb.brand_id', 'in', $val['relation_id'])
                        ->find();


                if ($goods_total['total_price'] < $val['use_condition']) {
                    unset($list[$key]);
                } else {
                    $brand_title = db('goods_brand')->where('brand_id', 'in', $val['relation_id'])->column('brand_title');
                    $val['name'] = '适用于' . implode(',', $brand_title) . '品牌商品';
                }
            }

            if ($val['range'] == 2) {

                $goods_total = db('cart')
                        ->fieldRaw('SUM(c.buy_num*ubg.selling_price) as total_price')
                        ->alias('c')
                        ->join('user_box_goods ubg', 'c.box_goods_id=ubg.box_goods_id')
                        ->join('goods g', 'ubg.goods_id=g.goods_id')
                        ->join('goods_cate gc', 'g.cate_id=gc.cate_id')
                        ->where('c.user_id', $user_id)
                        ->where('c.user_box_id', $user_box_id)
                        ->where('c.type', 0)
                        ->where('gc.cate_id', 'in', $val['relation_id'])
                        ->find();

                if ($goods_total['total_price'] < $val['use_condition']) {
                    unset($list[$key]);
                } else {
                    $cate_title = db('goods_cate')->where('cate_id', 'in', $val['relation_id'])->column('cate_title');
                    $val['name'] = '适用于' . implode(',', $cate_title) . '品类商品';
                }
            }
        }
    }

    return $list;
}

/**
 * 计算两个时间戳之间相差的日时分秒
 * @param $unixTime_1 开始时间戳
 * @param $unixTime_2 结束时间戳
 * @return array
 */
function timeDiff($unixTime_1, $unixTime_2) {
    $timediff = abs($unixTime_2 - $unixTime_1);
    //计算天数
    $days = intval($timediff / 86400);
    //计算小时数
    $remain = $timediff % 86400;
    $hours = intval($remain / 3600);
    //计算分钟数
    $remain = $remain % 3600;
    $mins = intval($remain / 60);
    //计算秒数
    $secs = $remain % 60;
    return ['day' => $days, 'hour' => $hours, 'min' => $mins, 'sec' => $secs];
}

/* function：计算两个日期相隔多少年，多少月，多少天
 * param string $date1[格式如：2011-11-5]
 * param string $date2[格式如：2012-12-01]
 * return array array('年','月','日');
 */

function diffDate($date1, $date2) {
    if (strtotime($date1) > strtotime($date2)) {
        $tmp = $date2;
        $date2 = $date1;
        $date1 = $tmp;
    }
    list($Y1, $m1, $d1) = explode('-', $date1);
    list($Y2, $m2, $d2) = explode('-', $date2);
    $y = (int) $Y2 - (int) $Y1;
    $m = (int) $m2 - (int) $m1;
    $d = (int) $d2 - (int) $d1;
    if ($d < 0) {
        $d += (int) date('t', strtotime("-1 month $date2"));
        if ($m != -11) {
            $m--;
        }
    }
    if ($m < 0) {
        $m += 12;
        $y--;
    }
    return array('year' => $y, 'month' => $m, 'day' => $d);
}
